﻿using System;
using System.ComponentModel;
using System.Collections.ObjectModel;
using DnnDash.SimplePhoneApp.Common;
using DnnDash.SimplePhoneApp.Model;
using System.Windows;
using System.Windows.Input;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.IO;
using System.Xml;

namespace DnnDash.SimplePhoneApp.ViewModel
{
    public class DashViewModel : ViewModelBase
    {
        #region properties

        private AppSettings appSettings;
        
        internal IDialogService DialogHelper { get; set; }
        internal INavigationService NavigationHelper { get; set; }
        private string _favoriteTabName = null;
        public string FavoriteTabName
        {
            get
            {
                return _favoriteTabName;
            }
            set
            {
                if (value != null)
                    value = value.Trim();

                if (_favoriteTabName != value)
                {
                    _favoriteTabName = value;

                    //check for match with favorite tab name
                    int index = 0;
                    foreach (ObservableDashGroups groups in DashControls)
                    {
                        string name = groups.GroupsName;
                        if (_favoriteTabName != null && name != null
                            && name.ToLower() == _favoriteTabName.ToLower())
                        {
                            //set the favorite index
                            this.FavoriteSelectedIndex = index;
                        }
                        index++;
                    }
                }
                RaisePropertyChanged("FavoriteTabName");
            }
        }

        public int FavoriteSelectedIndex { get; set; }
        private bool _favoriteLoaded;
        private bool _controlsLoaded;
        private string _pendingFavoriteTabName;
        private string version;
        public string Version
        {
            get
            {
                return version;
            }
            set
            {
                if (version != value)
                    version = value;

                RaisePropertyChanged("Version");
            }
        }

        private string versionOnServer = "Not connected.";
        public string VersionOnServer
        {
            get
            {
                return versionOnServer;
            }
            set
            {
                if (versionOnServer != value)
                    versionOnServer = value;

                RaisePropertyChanged("VersionOnServer");
            }
        }
        public const string IsLoadingPropertyName = "IsLoading";

        private bool _isLoading;

        public bool IsLoading
        {
            get
            {
                return _isLoading;
            }
            set
            {
                if (value != _isLoading)
                {
                    _isLoading = value;
                    RaisePropertyChanged(IsLoadingPropertyName);
                }
            }
        }
        public ObservableDashControls DashControls;
        
        #endregion

        #region constructors

        public DashViewModel()
        {
            // application settings
            appSettings = new AppSettings();

            // Note the version we're currently running...
            version = Helper.GetCurrentVersion().ToString();

            DashControls = new ObservableDashControls();
            if (string.IsNullOrEmpty(appSettings.DomainAlias) == false)
                DashControls.InstanceName = "DNN DASH " + appSettings.DomainAlias;
        }

        #endregion
        #region commands

        #endregion
        internal void GetFavoriteData()
        {
            //Uri favoriteUri = Helper.GetUri(appSettings.DomainAlias, "DnnDash_SimpleDashboard", "Dash", "FavoriteDashControl", false);
            //HttpWebRequest httpReq = (HttpWebRequest)HttpWebRequest.Create(favoriteUri);
            //httpReq.Credentials = new NetworkCredential(appSettings.Username, appSettings.Password);
            //httpReq.BeginGetResponse(HttpWebRequestCallBack, httpReq);

            //initialise a service Request object to call the web service
            Common.ServiceRequest<SimpleResult> getFavoriteTab = new ServiceRequest<SimpleResult>(appSettings, CallType.GET, "Json", "FavoriteDashControl", false, false);
            //configure event for return
            getFavoriteTab.CallReturned += new ServiceRequest<SimpleResult>.CallReturnedHandler(getFavoriteTab_CallReturned);
            //calls the web service
            getFavoriteTab.CallService();

        }
        internal void SaveFavoriteControl(string name)
        {
            _pendingFavoriteTabName = name;
            Common.ServiceRequest<SimpleResult> saveFavoriteTab = new ServiceRequest<SimpleResult>(appSettings, CallType.POST, "Json", "FavoriteDashControl", false, false);
            //simple JSON format by string formatting request, more complicated values would be done with JSON serialization
            string request = @"{ ""data"" : "" name "" } ".Replace("name", name);
            //set request body
            saveFavoriteTab.RequestBody = request;
            //configure event for return
            saveFavoriteTab.CallReturned += new ServiceRequest<SimpleResult>.CallReturnedHandler(saveFavoriteTab_CallReturned);
            //calls the web service
            saveFavoriteTab.CallService();
        }

        
        void getFavoriteTab_CallReturned(object sender, ServiceResponseEventArgs<SimpleResult> e)
        {
            _favoriteLoaded = true;
            if (_controlsLoaded && _favoriteLoaded && _isLoading)
                this.IsLoading = false;

            //response for the favorite Result get
            switch (e.StatusCode)
            {
                case HttpStatusCode.OK:
                    //everything worked OK, store the tab name in the viewmodel
                    SimpleResult result = e.ReturnValue;
                    //bind tab name
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        this.FavoriteTabName = result.data;
                    });
                    break;

                case HttpStatusCode.Unauthorized:
                    //error is incorrect username/password/authentication
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        DialogHelper.Show("Not Authorised to Access Service.  Please check username/password", "Unauthorized", DialogButton.OK);
                        NavigationHelper.GoToSettings();
                    });
                    break;
                case HttpStatusCode.NotFound:
                    //error is 404
                    if (DialogHelper != null)
                        DialogHelper.Show("Service was not found. Please check the domain settings.", "Service Not Found", DialogButton.OK);
                    if (NavigationHelper != null)
                        NavigationHelper.GoToSettings();
                    break;
                case HttpStatusCode.ServiceUnavailable:
                case HttpStatusCode.InternalServerError:
                    //error is 503/500 - server not working
                    if (DialogHelper != null)
                        DialogHelper.Show("Service returned an error. Please check the site for errors." , "Service Error", DialogButton.OK);
                    break;
                default:
                    //unknown error
                    if (DialogHelper != null)
                        DialogHelper.Show("Service returned an error.  Please Check the site for errors.\n" + e.ErrorMessage, "Service Error", DialogButton.OK);
                    break;
            }
        }

        void saveFavoriteTab_CallReturned(object sender, ServiceResponseEventArgs<SimpleResult> e)
        {
            switch (e.StatusCode)
            {
                case HttpStatusCode.OK:
                    //everything worked OK, store the tab name in the viewmodel
                    SimpleResult result = e.ReturnValue;
                    //saved OK, so update current favorite value

                    break;

                case HttpStatusCode.Unauthorized:
                    //error is incorrect username/password/authentication
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        DialogHelper.Show("Not Authorised to Save Setting to Server.  Please check username/password.  The setting was not saved.", "Unauthorized", DialogButton.OK);
                        NavigationHelper.GoToSettings();
                    });
                    break;
                case HttpStatusCode.NotFound:
                    //error is 404
                    DialogHelper.Show("Service was not found. Please check the domain settings. The setting was not saved.", "Service Not Found", DialogButton.OK);
                    NavigationHelper.GoToSettings();
                    break;
                case HttpStatusCode.ServiceUnavailable:
                case HttpStatusCode.InternalServerError:
                    //error is 503/500 - server not working
                    DialogHelper.Show("Service returned an error. Please check the site for errors.  The setting was not saved.", "Service Error", DialogButton.OK);
                    break;
            }
        }

        internal void GetControlsData()
        {

            //initialise a service Request object to call the web service
            Common.ServiceRequest<XDocument> getControlsData = new ServiceRequest<XDocument>(appSettings, CallType.GET, "xml", "Controls", false, false);
            //configure event for return
            getControlsData.CallReturned += new ServiceRequest<XDocument>.CallReturnedHandler(getControlsData_CallReturned);
            //calls the web service
            getControlsData.CallService();

        }
        void getControlsData_CallReturned(object sender, ServiceResponseEventArgs<XDocument> e)
        {
            _controlsLoaded = true;
            switch (e.StatusCode)
            {

                case HttpStatusCode.OK:
                    XDocument result = e.ReturnValue;
                    string xml = result.ToString();
                    string error = null;
                    if (BindControlDataToScreen(xml, out error) == false)
                    {
                        ShowErrorMessage(error);
                    }
                    break;
                case HttpStatusCode.NotFound:
                    //error is 404
                    DialogHelper.Show("Service was not found. Please check the domain settings. The dashboard data was not retrieved.", "Service Not Found", DialogButton.OK);
                    NavigationHelper.GoToSettings();
                    break;
                case HttpStatusCode.ServiceUnavailable:
                case HttpStatusCode.InternalServerError:
                    //error is 503/500 - server not working
                    DialogHelper.Show("Service returned an error. Please check the site for errors.  The dashboard data was not retrieved.", "Service Error", DialogButton.OK);
                    break;

            }
            
            if (_controlsLoaded && _favoriteLoaded && _isLoading)
                this.IsLoading = false;
        }
 
        public void DashboardDataFromService()
        {
            
            if (appSettings.CredentialsExist)
            {
                this.IsLoading = true;
                GetFavoriteData();
                GetControlsData();
            }
            else
            {
                if (!StateUtilities.IsLaunching)
                    MessageBox.Show("Unable to connect to the server. Please check your settings and try again.", "Connection...", MessageBoxButton.OK);

                NavigationHelper.GoToSettings();
            }
        }

        private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            _controlsLoaded = true;
            if (e.Error != null)
            {
                ShowErrorMessage(e.Error.Message);
            }
            else
            {
                //hacking up response for testing, just comment this out for an example xml return value
                //string xml = @"<dashboard><dashControl name=""Web Server""><server><osVersion>Microsoft Windows NT 6.1.7601 Service Pack 1</osVersion><iisVersion>Microsoft-IIS/7.5</iisVersion><framework>4.0.30319.269</framework><identity>NT AUTHORITY\NETWORK SERVICE</identity><hostName>p2470223</hostName><physicalPath>D:\HTTP\dnndash.com\httpdocs</physicalPath><url>dnndash.com</url><relativePath>/</relativePath></server></dashControl><dashControl name=""Host""><host><hostGUID>C20F2D59-033D-4851-9E96-66F8EEDF8318</hostGUID><version>6.2.1</version><permissions>ReflectionPermission, WebPermission, AspNetHostingPermission</permissions><dataProvider>SqlDataProvider</dataProvider><cachingProvider>FileBasedCachingProvider</cachingProvider><friendlyUrlProvider>DNNFriendlyUrl</friendlyUrlProvider><friendlyUrlEnabled>True</friendlyUrlEnabled><friendlyUrlType>humanfriendly</friendlyUrlType><htmlEditorProvider>DotNetNuke.RadEditorProvider</htmlEditorProvider><loggingProvider>DBLoggingProvider</loggingProvider><schedulerMode>REQUEST_METHOD</schedulerMode><webFarmEnabled>False</webFarmEnabled><JQueryVersion>1.6.4</JQueryVersion><JQueryUIVersion>1.8.16</JQueryUIVersion></host></dashControl><dashControl name=""Websites""><portals><portal><portalName>Dnn Dashboard</portalName><GUID>e552bc82-5beb-4b47-99ce-491cbe733d52</GUID><pages>31</pages><users>2</users><roles>5</roles></portal></portals></dashControl><dashControl name=""Modules""><installedModules><module><moduleName>Authentication</moduleName><friendlyName>Account Login</friendlyName><version>06.02.00</version><instances>0</instances></module><module><moduleName>Banners</moduleName><friendlyName>Banners</friendlyName><version>06.02.00</version><instances>0</instances></module><module><moduleName>ConfigurationManager</moduleName><friendlyName>Configuration Manager</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>Console</moduleName><friendlyName>Console</friendlyName><version>06.02.00</version><instances>6</instances></module><module><moduleName>DDRMenu</moduleName><friendlyName>DDR Menu</friendlyName><version>02.00.02</version><instances>0</instances></module><module><moduleName>51Degrees.mobi</moduleName><friendlyName>DotNetNuke Client Capability Provider</friendlyName><version>06.02.01</version><instances>1</instances></module><module><moduleName>FeedExplorer</moduleName><friendlyName>Feed Explorer</friendlyName><version>06.02.00</version><instances>0</instances></module><module><moduleName>FileManager</moduleName><friendlyName>File Manager</friendlyName><version>06.02.00</version><instances>2</instances></module><module><moduleName>GoogleAnalytics</moduleName><friendlyName>Google Analytics</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>DNN_HTML</moduleName><friendlyName>HTML</friendlyName><version>06.02.01</version><instances>35</instances></module><module><moduleName>Journal</moduleName><friendlyName>Journal</friendlyName><version>06.02.01</version><instances>1</instances></module><module><moduleName>Languages</moduleName><friendlyName>Languages</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>Lists</moduleName><friendlyName>Lists</friendlyName><version>06.02.00</version><instances>2</instances></module><module><moduleName>LogViewer</moduleName><friendlyName>Log Viewer</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>DotNetNuke.Modules.MemberDirectory</moduleName><friendlyName>Member Directory</friendlyName><version>06.02.01</version><instances>5</instances></module><module><moduleName>DotNetNuke.Modules.CoreMessaging</moduleName><friendlyName>Message Center</friendlyName><version>06.02.01</version><instances>1</instances></module><module><moduleName>Newsletters</moduleName><friendlyName>Newsletters</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>Tabs</moduleName><friendlyName>Pages</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>DotNetNuke.RadEditorProvider</moduleName><friendlyName>RadEditor Manager</friendlyName><version>06.02.01</version><instances>1</instances></module><module><moduleName>RecycleBin</moduleName><friendlyName>Recycle Bin</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>SearchInput</moduleName><friendlyName>Search Input</friendlyName><version>06.02.00</version><instances>0</instances></module><module><moduleName>SearchResults</moduleName><friendlyName>Search Results</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>SiteLog</moduleName><friendlyName>Site Log</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>SiteWizard</moduleName><friendlyName>Site Wizard</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>Sitemap</moduleName><friendlyName>Sitemap</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>Skins</moduleName><friendlyName>Skins</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>Social Groups</moduleName><friendlyName>Social Groups</friendlyName><version>06.02.01</version><instances>0</instances></module><module><moduleName>Solutions</moduleName><friendlyName>Solutions</friendlyName><version>06.02.00</version><instances>0</instances></module><module><moduleName>DotNetNuke.Taxonomy</moduleName><friendlyName>Taxonomy Manager</friendlyName><version>06.02.01</version><instances>1</instances></module><module><moduleName>Security</moduleName><friendlyName>Users And Roles</friendlyName><version>06.02.00</version><instances>3</instances></module><module><moduleName>Vendors</moduleName><friendlyName>Vendors</friendlyName><version>06.02.00</version><instances>2</instances></module><module><moduleName>ViewProfile</moduleName><friendlyName>ViewProfile</friendlyName><version>06.02.00</version><instances>9</instances></module></installedModules></dashControl><dashControl name=""Skins""><installedSkins><skin><skinName>DarkKnight</skinName><inUse>True</inUse></skin><skin><skinName>DarkKnightMobile</skinName><inUse>True</inUse></skin></installedSkins></dashControl></dashboard>";
                string xml = e.Result;
                string error = null;
                if (BindControlDataToScreen(xml, out error) == false)
                {
                    ShowErrorMessage(error);
                }
                
            }
            if (_controlsLoaded && _favoriteLoaded && _isLoading)
                this.IsLoading = false;
        }

        private bool  BindControlDataToScreen(string xml, out string errorMessage)
        {

            /* Example Xml expected from server
             * <dashboard>
             *  <dashControl name="Web Server">
             *      <server>
             *          <osVersion>Microsoft Windows NT 6.1.7601 Service Pack 1</osVersion>
             * <dashboard>
             *  <dashControl name="Web Server">
             *      <server>
             *          <osVersion>Microsoft Windows NT 6.1.7601 Service Pack 1</osVersion>
             *          <iisVersion>Microsoft-IIS/7.5</iisVersion>
             *          <framework>4.0.30319.269</framework>
             *          <identity>NT AUTHORITY\NETWORK SERVICE</identity>
             *          <hostName>p2470223</hostName>
             *          <physicalPath>D:\HTTP\dnndash.com\httpdocs</physicalPath>
             *          <url>dnndash.com</url>
             *          <relativePath>/</relativePath>
             *      </server>
             *   </dashControl>
             * <dashControl name="Host">
             *  <host>
             *      <hostGUID>C20F2D59-033D-4851-9E96-66F8EEDF8318</hostGUID>
             *      <version>6.2.1</version><permissions>ReflectionPermission, WebPermission, AspNetHostingPermission</permissions>
             *      <dataProvider>SqlDataProvider</dataProvider>
             *      <cachingProvider>FileBasedCachingProvider</cachingProvider>
             *      <friendlyUrlProvider>DNNFriendlyUrl</friendlyUrlProvider>
             *      <friendlyUrlEnabled>True</friendlyUrlEnabled>
             *      <friendlyUrlType>humanfriendly</friendlyUrlType>
             *      <htmlEditorProvider>DotNetNuke.RadEditorProvider</htmlEditorProvider>
             *      <loggingProvider>DBLoggingProvider</loggingProvider>
             *      <schedulerMode>REQUEST_METHOD</schedulerMode>
             *      <webFarmEnabled>False</webFarmEnabled>
             *      <JQueryVersion>1.6.4</JQueryVersion>
             *      <JQueryUIVersion>1.8.16</JQueryUIVersion>
             *      </host>
             * </dashControl>
             * <dashControl name="Websites">
             *  <portals>
             *      <portal>
             *          <portalName>Dnn Dashboard</portalName>
             *          <GUID>e552bc82-5beb-4b47-99ce-491cbe733d52</GUID><pages>31</pages><users>2</users><roles>5</roles></portal></portals></dashControl><dashControl name="Modules"><installedModules><module><moduleName>Authentication</moduleName><friendlyName>Account Login</friendlyName><version>06.02.00</version><instances>0</instances></module><module><moduleName>Banners</moduleName><friendlyName>Banners</friendlyName><version>06.02.00</version><instances>0</instances></module><module><moduleName>ConfigurationManager</moduleName><friendlyName>Configuration Manager</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>Console</moduleName><friendlyName>Console</friendlyName><version>06.02.00</version><instances>6</instances></module><module><moduleName>DDRMenu</moduleName><friendlyName>DDR Menu</friendlyName><version>02.00.02</version><instances>0</instances></module><module><moduleName>51Degrees.mobi</moduleName><friendlyName>DotNetNuke Client Capability Provider</friendlyName><version>06.02.01</version><instances>1</instances></module><module><moduleName>FeedExplorer</moduleName><friendlyName>Feed Explorer</friendlyName><version>06.02.00</version><instances>0</instances></module><module><moduleName>FileManager</moduleName><friendlyName>File Manager</friendlyName><version>06.02.00</version><instances>2</instances></module><module><moduleName>GoogleAnalytics</moduleName><friendlyName>Google Analytics</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>DNN_HTML</moduleName><friendlyName>HTML</friendlyName><version>06.02.01</version><instances>35</instances></module><module><moduleName>Journal</moduleName><friendlyName>Journal</friendlyName><version>06.02.01</version><instances>1</instances></module><module><moduleName>Languages</moduleName><friendlyName>Languages</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>Lists</moduleName><friendlyName>Lists</friendlyName><version>06.02.00</version><instances>2</instances></module><module><moduleName>LogViewer</moduleName><friendlyName>Log Viewer</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>DotNetNuke.Modules.MemberDirectory</moduleName><friendlyName>Member Directory</friendlyName><version>06.02.01</version><instances>5</instances></module><module><moduleName>DotNetNuke.Modules.CoreMessaging</moduleName><friendlyName>Message Center</friendlyName><version>06.02.01</version><instances>1</instances></module><module><moduleName>Newsletters</moduleName><friendlyName>Newsletters</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>Tabs</moduleName><friendlyName>Pages</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>DotNetNuke.RadEditorProvider</moduleName><friendlyName>RadEditor Manager</friendlyName><version>06.02.01</version><instances>1</instances></module><module><moduleName>RecycleBin</moduleName><friendlyName>Recycle Bin</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>SearchInput</moduleName><friendlyName>Search Input</friendlyName><version>06.02.00</version><instances>0</instances></module><module><moduleName>SearchResults</moduleName><friendlyName>Search Results</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>SiteLog</moduleName><friendlyName>Site Log</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>SiteWizard</moduleName><friendlyName>Site Wizard</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>Sitemap</moduleName><friendlyName>Sitemap</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>Skins</moduleName><friendlyName>Skins</friendlyName><version>06.02.00</version><instances>1</instances></module><module><moduleName>Social Groups</moduleName><friendlyName>Social Groups</friendlyName><version>06.02.01</version><instances>0</instances></module><module><moduleName>Solutions</moduleName><friendlyName>Solutions</friendlyName><version>06.02.00</version><instances>0</instances></module><module><moduleName>DotNetNuke.Taxonomy</moduleName><friendlyName>Taxonomy Manager</friendlyName><version>06.02.01</version><instances>1</instances></module><module><moduleName>Security</moduleName><friendlyName>Users And Roles</friendlyName><version>06.02.00</version><instances>3</instances></module><module><moduleName>Vendors</moduleName><friendlyName>Vendors</friendlyName><version>06.02.00</version><instances>2</instances></module><module><moduleName>ViewProfile</moduleName><friendlyName>ViewProfile</friendlyName><version>06.02.00</version><instances>9</instances></module></installedModules></dashControl><dashControl name="Skins"><installedSkins><skin><skinName>DarkKnight</skinName><inUse>True</inUse></skin><skin><skinName>DarkKnightMobile</skinName><inUse>True</inUse></skin></installedSkins></dashControl></dashboard>";
             */
            bool result = false;
            try
            {
                
                errorMessage = null;
                StringReader stringReader = new StringReader(xml);
                XmlReader xmlReader = XmlReader.Create(stringReader);
                XDocument doc = XDocument.Load(xmlReader);
                //get root level xml document
                XElement dashboardEl = doc.Element("dashboard");
                if (dashboardEl != null && dashboardEl.HasElements)
                {
                    //mvvm binding
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        //clear out existing values, building all-new lists
                        DashControls.Clear();
                        //top-level controls, equates to a dash control in the DotNetNuke Dashboard
                        foreach (XElement dashCtlEl in dashboardEl.Elements()) //control level 'web server'
                        {
                            string name = GetSafeAttributeValue(dashCtlEl, "name"); //get the name of the control
                            foreach (XElement topSettingEl in dashCtlEl.Elements())  //setting level 'server' - in reality contains all of the control settings
                            {
                                XElement settingsParent = topSettingEl;
                                if (topSettingEl.HasElements)
                                {
                                    //setting is below one more level
                                    BuildSettingsList(name, topSettingEl);
                                }
                            }
                        }
                    });
                    result = true;
                }
                else
                {
                    result = false;
                    errorMessage = "Dashboard has no contents or format is not recognised";
                }
            }
            catch (Exception ex)
            {
                errorMessage = "Exception : " + ex.Message;
                result = false;
            }
            return result ;
        }
        private void BuildSettingsList(string name, XElement settingsParent)
        {
            bool first = true;
            //initialise the settings collection
            ObservableDashSettings hostLevelSettings = new ObservableDashSettings();
            //initialise the settings groups, which are a container for the lists of settings
            ObservableDashGroups settingsGroups = new ObservableDashGroups();
            //set the parent name (equates to the type of settings)
            hostLevelSettings.SettingsParentName = name;
            settingsGroups.GroupsName = name;
            int index = 0;
            foreach (XElement hostLevelSetting in settingsParent.Elements())
            {
                //settings can either be at the 'host' (top level - ie, host settings etc)
                if (hostLevelSetting.HasElements == false)
                {
                    //extract setting from xml and build up list of host level settings
                    string settingName = hostLevelSetting.Name.ToString();
                    string settingValue = hostLevelSetting.Value;
                    DashSetting settingVal = new DashSetting() { SettingName = settingName, SettingValue = settingValue };
                    hostLevelSettings.IsExpanded = true;
                    hostLevelSettings.Add(settingVal);

                }
                else
                {
                    //or settings cna be grouped under sub-headings-  module, portal, skin, etc
                    string subHostSettingsName = hostLevelSetting.Name.ToString();
                    ObservableDashSettings subHostSettings = new ObservableDashSettings();
                    bool firstSetting = true;
                    foreach (XElement subHostLevelSetting in hostLevelSetting.Elements())
                    {
                        //iterate each specific setting in this group of sub-level settings
                        //extract and add to settings list
                        string settingName = subHostLevelSetting.Name.ToString();
                        string settingValue = subHostLevelSetting.Value;
                        if (firstSetting && string.IsNullOrEmpty(settingValue) == false)
                            subHostSettingsName += " : " + settingValue;    
                        
                        DashSetting settingVal = new DashSetting() { SettingName = settingName, SettingValue = settingValue };
                        subHostSettings.Add(settingVal);
                        firstSetting = false;
                    }
                    if (subHostSettings.Count > 0)
                    {
                        //name with name customised
                        subHostSettings.SettingsParentName = subHostSettingsName;
                        hostLevelSettings.IsExpanded = first;
                        settingsGroups.Add(subHostSettings);
                    }
                }
                first = false;
                index++;
            }
            if (hostLevelSettings.Count > 0)
            {
                //for host levels settings, the settingsGroup only contains one lot
                settingsGroups.Add(hostLevelSettings);
                DashControls.Add(settingsGroups);
            }
            else
            {
                //for sub-host level settings, the settingsGroup has already been populated
                if (settingsGroups.Count > 0)
                    DashControls.Add(settingsGroups);
            }
        }
        private string GetSafeAttributeValue(XElement el, string attName)
        {
            var result = (string)el.Attribute(attName);
            return result.ToString();
        }
        
        
        #region helpers

        private void ShowErrorMessage(string message)
        {
            // Dispatch the message
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                if (message == null) message = "Error message was null";
                MessageBox.Show(message, "Error", MessageBoxButton.OK);
            });
        }

        #endregion


        
    }
}
